const express = require('express')
const multer = require('multer')
const cors = require('cors')
const fs = require('fs')
const path = require('path')

const app = express()
const UPLOAD_DIR = path.resolve(__dirname, 'upload')

// 存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const { hash } = req.body
    const chunkDir = path.resolve(UPLOAD_DIR, hash)
    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir)
    }
    cb(null, chunkDir)
  },
  filename: (req, file, cb) => {
    const { index } = req.body
    cb(null, `${index}`)
  }
})

const upload = multer({ storage })

// 检查分片
app.get('/check', (req, res) => {
  const { hash, total } = req.query
  const chunkDir = path.resolve(UPLOAD_DIR, hash)

  if (!fs.existsSync(chunkDir)) {
    return res.json({ uploaded: [] })
  }

  const uploaded = fs.readdirSync(chunkDir).map((name) => parseInt(name))
  res.json({ uploaded })
})

// 上传分片
app.post('/upload', upload.single('chunk'), (req, res) => {
  setTimeout(() => {
    res.json({ success: true })
  }, 1000)
})

// 合并分片
app.post('/merge', async (req, res) => {
  // const { hash, total, filename } = req.body
  // const chunkDir = path.resolve(UPLOAD_DIR, hash)
  // const filePath = path.resolve(UPLOAD_DIR, filename)

  // // 确保所有分片都存在
  // for (let i = 0; i < total; i++) {
  //   if (!fs.existsSync(path.resolve(chunkDir, i.toString()))) {
  //     return res.status(400).json({ error: '缺少分片' })
  //   }
  // }

  // // 创建写入流
  // const writeStream = fs.createWriteStream(filePath)

  // // 按顺序合并分片
  // for (let i = 0; i < total; i++) {
  //   const chunkPath = path.resolve(chunkDir, i.toString())
  //   const chunk = fs.readFileSync(chunkPath)
  //   writeStream.write(chunk)
  //   fs.unlinkSync(chunkPath) // 删除分片
  // }

  // writeStream.end()
  // fs.rmdirSync(chunkDir) // 删除分片目录

  res.json({ success: true })
})

app.use(cors({ origin: 'http://localhost:3006' }))
app.use(express.urlencoded({ extended: false }));

app.listen(3000, () => {
  console.log(`Server is running on port 3000`)
})
